/* eslint-disable prettier/prettier */
import React, { createRef, PureComponent, useState, useRef, useEffect } from 'react';
import { View, Text, TextInput, FlatList, StyleSheet, SafeAreaView, Keyboard, Image, TouchableWithoutFeedback, TouchableHighlight, TouchableOpacity, PermissionsAndroid } from 'react-native';
import { syncPageGetFriendMsg, syncPageGetFriendMsgSeq, SetCuurentPersonalFriendPageInfo, SetPersonalFriendPageMsgItem, asyncGetFriendList, SetFriendMsg } from "../../redux/features/appSlice"
import { connect } from 'react-redux'
import 'dayjs/locale/zh-cn';
import { pTx } from "../../utils/dimensions"
import { debounce } from "../../utils/useDebounce"
import { realm, schemaName } from "../../utils/schema"
import { getLaunchImageLibrary } from "../../utils/launchImageLibrary"
import Realm from "realm"
import { formatFriendMsg } from "../../utils/formatFriendMsg"
import VoicePressable from "../../components/voicePressable"
import httpApi from "../../api"
import ImageEquallyEnlarge from "../../components/imageEquallyEnlarge"
import ImageEquallyEnlargeVideo from "../../components/imageEquallyEnlargeVideo"
import PersonalBusinessCard from "../../components/personalBusinessCard"
import FriendTransferInApp from "../../components/friendTransferInApp"
import FriendGrabRedPacket from "../../components/friendGrabRedPacket"
import FriendRedPacketInApp from "../../components/friendRedPacketInApp"
import { showModal } from "../../components/rootSiblings/showModal"
import NavigateModalSelect from "../../components/rootSiblings/navigateModalSelect"
import PlayVoice from "../../components/playVoice"
import EmojiSelectorList from "../../components/emojiSelectorList"
import ImageView from "react-native-image-viewing";
import AudioRecorderPlayer from 'react-native-audio-recorder-player';
const audioRecorderPlayer = new AudioRecorderPlayer();

/**
 *  100 条历史消息，先给 10 条最新的，再给 10 条
 *  也就是先给 91 - 100, 再给 81 - 90, 依次类推
 */
const getData = (page, size, msgLis, setMsgLis, props) => {
    return new Promise(resolve => {
        const allData = msgLis
        const newRes = allData.slice(page * size, page * size + size).reverse();
        resolve(newRes);
    });
};

const isAuthor = (id) => !(id > 0)
const RenderItemInfo = (props) => {
    const { item, index, updateParentState, playVoiceRefs } = props
    const M = item.M?.split(' ')
    switch (item.MT) {
        case 0:
            return <Text style={styles.messageText} selectable>{item.M}</Text>
        case 42:
            return <Text style={styles.messageText} selectable>{item.M}</Text>
        case 2:
            return <TouchableWithoutFeedback onPress={() => {
                updateParentState({
                    visible: true,
                    images: [
                        {
                            uri: httpApi.inline + M[1]
                        }
                    ]
                })
            }}>
                <View>
                    <ImageEquallyEnlarge
                        style={styles.imageEqually}
                        source={{ uri: httpApi.inline + M[1] }}
                        width={pTx(100)}
                    />
                </View>
            </TouchableWithoutFeedback>
        case 3:
            return <ImageEquallyEnlargeVideo {...props} style={styles.imageEqually}
                source={require('../../assets/image/icon36.png')}
                width={pTx(120)}></ImageEquallyEnlargeVideo>
        case 5:
            return <TouchableWithoutFeedback onPress={() => props.onStopPlayDebounce(item, item._id)}>
                <View>
                    <PlayVoice
                        ref={(ref) => {
                            props.playVoiceRefs[item._id] = ref;
                        }}
                        {...props}
                        item={item}
                    />
                </View>
            </TouchableWithoutFeedback>
        case 6:
            return <PersonalBusinessCard {...props} item={item} />
        case 7:
            return <FriendTransferInApp {...props} item={item} />
        case 9:
            return <FriendGrabRedPacket {...props} item={item} />
        case 14:
            return <View style={styles.RedPacketBox}>
                {
                    item.S == -1 ?
                        <Text style={styles.RedPacket}>你领取了{props.route.params.R}的<Text style={[{ color: "#F35E4D" }]}>红包</Text></Text>
                        :
                        <Text style={styles.RedPacket}>{props.route.params.R}领取了你的<Text style={[{ color: "#F35E4D" }]}>红包</Text></Text>
                }
            </View>
    }
}
const DetailScreen = (props, state, playVoiceRefs) => {
    /**
     * 分页字段
     * page
     * size
     * total，根据 total 判断是否还有更多数据
     */
    const curPageRef = useRef(1);
    const SIZE = 20;
    const [msgLis, setMsgLis] = useState(JSON.parse(JSON.stringify(realm.objects(schemaName.FriendMsgLis).filtered(`F == ${props.state.id} and UserId == ${props.userInfo.Id}`).sorted('T', true))));
    const [data, setData] = useState(msgLis.slice(0, SIZE));
    useEffect(() => {
        setData([props.personalFriendPageMsgItem, ...data]);
    }, [props.personalFriendPageMsgItem])

    const handleOnEndReached = () => {
        getData(curPageRef.current, SIZE, msgLis, setMsgLis, props).then(res => {
            res.reverse();
            setData([...data, ...res]);
        });
        curPageRef.current += 1;
    };
    const renderItem = ({ item, index }) => {
        return (item.F && <View>
            <View style={[styles.renderUserItem, isAuthor(item.S) && styles.renderUserItemRowReverse]}>
                {(item.MT != 14) && <View style={styles.renderAvatar}>
                    <TouchableWithoutFeedback onPress={() => {
                        var userInfo
                        if (!isAuthor(item.S)) {
                            userInfo = {
                                Id: props.route.params.F,
                                NickName: props.route.params.R,
                                ProfilePhoto: props.route.params.P,
                                Ms: props.route.params
                            }
                        } else {
                            userInfo = props.userInfo
                        }
                        props.navigation.navigate('friendInfo', userInfo)
                    }}>
                        <Image style={[styles.avatar]} source={{ uri: httpApi.inline + ((isAuthor(item.S) ? props.userInfo.ProfilePhoto : props.route.params.P) || httpApi.defaultAvatar) }}></Image>
                    </TouchableWithoutFeedback>
                </View>
                }
                <RenderItemInfo {...props} item={item} />
            </View>
            {item.SendState == 3 && <Text style={styles.youNotFriendText}>你还不是他（她）朋友。请先发送朋友验证请求，对方验证通过后，才能聊天</Text>}
        </View>
        )
    }
    const keyboardDismiss = () => Keyboard.dismiss();
    return (
        <FlatList
            style={{ flex: 1 }}
            onEndReached={handleOnEndReached}
            // onEndReachedThreshold={10}
            renderItem={renderItem}
            contentContainerStyle={{
                // flexGrow: 1,
                // justifyContent: 'flex-end',
            }}
            inverted
            data={data}
            onScroll={keyboardDismiss}
            initialNumToRender={20}
            keyExtractor={(item, index) => item._id || index}
        />
    );
};
export class FriendMsg extends PureComponent {
    constructor(props) {
        super(props)
        this.state = {
            text: "",
            id: props.route.params.F,
            messages: [],
            refreshing: false,
            loading: true,
            openEmoji: false,
            isTextVoice: true,
            moreFeaturesOpen: false,
            composerText: null,
            playVoiceRefsIndex: null,
            MsgLis: [],
            currentPage: 1,
            pageSize: 1000000,
            personalFriendPageMsgItem: props.personalFriendPageMsgItem,

            images: [],
            visible: false
        }
        this.playVoiceRefs = []
        this.sendRedPacketInRefs = createRef();

    }
    async componentDidMount(prevProps, prevState) {
        this.props.navigation.setOptions({
            headerTitle: ({ options }) => (
                <Text style={styles.headerTitle} ellipsizeMode={'tail'} numberOfLines={1}>{this.props.route.params.R}</Text>
            )
        });
        setTimeout(async () => {
            this.props.SetCuurentPersonalFriendPageInfo(this.props.route.params)
            this.props.syncPageGetFriendMsgSeq(this.state.id, this.props.userInfo.Id)

            this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', () => {
                this.setState({ moreFeaturesOpen: false, openEmoji: false })
            });
            this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', Keyboard.dismiss);

            //更新通讯录个人信息是否修改头像名称
            httpApi.getFriendInfo({ id: this.state.id }).then(res => {
                this.props.asyncGetFriendList(this.props.userInfo.Id)
            })

            if (Platform.OS === 'android') {
                try {
                    const grants = await PermissionsAndroid.requestMultiple([
                        PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
                        PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
                        PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,
                    ]);
                    if (
                        grants['android.permission.WRITE_EXTERNAL_STORAGE'] ===
                        PermissionsAndroid.RESULTS.GRANTED &&
                        grants['android.permission.READ_EXTERNAL_STORAGE'] ===
                        PermissionsAndroid.RESULTS.GRANTED &&
                        grants['android.permission.RECORD_AUDIO'] ===
                        PermissionsAndroid.RESULTS.GRANTED
                    ) {
                    } else {
                        return;
                    }
                } catch (err) {
                    return;
                }
            }
        })
    }
    componentWillUnmount() {
        this.keyboardDidShowListener?.remove();
        this.keyboardDidHideListener?.remove();
        this.props.SetCuurentPersonalFriendPageInfo({})
        this.props.syncPageGetFriendMsg({})
        this.props.syncPageGetFriendMsgSeq(this.state.id, this.props.userInfo.Id)
    }
    updateState(data) {
        this.setState(data);
    }
    async onTextSend() {
        try {
            var timestamp = Date.parse(new Date()) / 1000
            const realmItem = {
                F: this.state.id,
                M: this.state.text,
                MT: 0,
                S: -1,
                T: timestamp,
                _id: new Realm.BSON.UUID(),
                Unread: 0,
                SendState: this.props.route.params.State == 0 ? 3 : 0,
                UserId: this.props.userInfo.Id
            }
            this.setState({ text: "" })

            realm.write(() => {
                realm.create(schemaName.FriendMsgLis, realmItem, true);
            })

            this.props.syncPageGetFriendMsg(realmItem)
            const res = await httpApi.sendFriendText({ message: realmItem.M, id: this.state.id })
        } catch (error) {
        }
    }
    sendFriendFile = async () => {
        try {
            let File = await getLaunchImageLibrary()
            File = File.uri ? File : File[0]
            const msgType = File.type == 'image/jpeg' ? 2 : 3
            var timestamp = Date.parse(new Date()) / 1000
            let MsgLisLength = new Realm.BSON.UUID()
            const image = await httpApi.uploadMinio(File)
            const realmItem = {
                F: this.state.id,
                M: File.fileSize + " " + image.data.FileNames[0] + " " + File.fileName,
                MT: msgType,
                T: timestamp,
                S: -1,
                _id: MsgLisLength,
                Unread: 0,
                SendState: this.props.route.params.State == 0 ? 3 : 0,
                UserId: this.props.userInfo.Id
            }
            this.props.syncPageGetFriendMsg(realmItem)
            realm.write(() => {
                realm.create(schemaName.FriendMsgLis, realmItem, true);
            })
            await httpApi.sendFriendFile({
                id: this.state.id,
                msgType,
                srcFileName: File.fileName,
                dstFileName: image.data.FileNames[0],
                fileSize: File.fileSize
            })
        } catch (error) {
            console.log(error)
        }
    }
    sendFriendContactCard = async () => {
        try {
            const res = await httpApi.sendFriendContactCard({
                id: this.state.id,
                friendId: this.props.userInfo.Id,
            })
            var timestamp = Date.parse(new Date()) / 1000
            const realmItem = {
                F: this.state.id,
                M: res.data.FriendInfo,
                MT: 6,
                S: -1,
                T: timestamp,
                _id: new Realm.BSON.UUID(),
                Unread: 0,
                UserId: this.props.userInfo.Id
            }
            this.props.syncPageGetFriendMsg(realmItem)
            realm.write(() => {
                realm.create(schemaName.FriendMsgLis, realmItem, true);
            })
        } catch (error) {
            console.log(error)
        }
    }
    onStopPlayDebounce = debounce(async ([item, index]) => {
        audioRecorderPlayer.stopPlayer();
        audioRecorderPlayer.removePlayBackListener();
        this.playVoiceRefs[this.state.playVoiceRefsIndex]?.onStopPlay()
        if (!item) return this.setState({ playVoiceRefsIndex: null })
        const [time, uri] = item?.M?.split(' ')
        if (this.state.playVoiceRefsIndex != index) {
            this.setState({ playVoiceRefsIndex: index })
            await audioRecorderPlayer.startPlayer(httpApi.inline + uri);
            this.playVoiceRefs[index]?.onStartPlay()
        } else {
            this.setState({ playVoiceRefsIndex: null })
        }
    }, 100, false)
    render() {
        return (
            <View style={styles.mainContent}>
                <DetailScreen {...this.props} state={this.state} updateParentState={this.updateState.bind(this)} onStopPlayDebounce={this.onStopPlayDebounce.bind(this)} playVoiceRefs={this.playVoiceRefs} />
                <View style={styles.footRender}>
                    <View style={styles.footRenderRow}>
                        <TouchableOpacity onPress={() => {
                            this.setState({ isTextVoice: this.state.isTextVoice ? false : true, moreFeaturesOpen: false })
                        }}>
                            <View style={[{ marginLeft: pTx(8) }]}>
                                <Image style={[styles.footImage]} source={this.state.isTextVoice ? require('../../assets/image/icon35.png') : require('../../assets/image/icon13.png')}></Image>
                            </View>
                        </TouchableOpacity>
                        <View style={styles.renderComposer}>
                            {!this.state.isTextVoice ? <TextInput value={this.state.text} onChangeText={(e) => this.setState({ text: e })} style={[styles.composer, { height: this.state.height }]} multiline maxLength={200}
                            />
                                :
                                <VoicePressable
                                    {...this.props}
                                    onStopPlayDebounce={() => this.onStopPlayDebounce(null, this.state.playVoiceRefsIndex)} />
                            }
                        </View>
                        <View style={styles.rightRenderSend}>
                            <TouchableOpacity onPress={() => {
                                Keyboard.dismiss();
                                setTimeout(() => {
                                    this.setState({
                                        openEmoji: this.state.openEmoji ? false : true,
                                        moreFeaturesOpen: false,
                                        isTextVoice: false
                                    })
                                }, 100)
                            }}>
                                <Image style={[styles.footImage]} source={require('../../assets/image/icon12.png')}></Image>
                            </TouchableOpacity>
                            {!this.state.text ? <TouchableOpacity onPress={() => {
                                Keyboard.dismiss();
                                setTimeout(() => {
                                    this.setState({
                                        moreFeaturesOpen: this.state.moreFeaturesOpen ? false : true,
                                        openEmoji: false,
                                        isTextVoice: true
                                    })
                                }, 100)
                            }}>
                                <Image style={[styles.footImage]} source={require('../../assets/image/icon14.png')}></Image>
                            </TouchableOpacity>
                                :
                                <Text style={[styles.sendBtn]} onPress={() => this.onTextSend()}>
                                    发送
                                </Text>
                            }
                        </View>
                    </View>
                    <View>
                        {this.state.moreFeaturesOpen && <View style={[styles.moreFeatures]}>
                            <TouchableWithoutFeedback onPress={() => this.sendFriendFile()}>
                                <View style={[styles.featuresCell]}>
                                    <Image style={styles.featuresImage} source={require('../../assets/image/icon26.png')}></Image>
                                    <Text style={styles.featuresTexy}>图片</Text>
                                </View>
                            </TouchableWithoutFeedback>
                            <TouchableWithoutFeedback>
                                <View style={[styles.featuresCell]}>
                                    <Image style={styles.featuresImage} source={require('../../assets/image/icon27.png')}></Image>
                                    <Text style={styles.featuresTexy}>文件</Text>
                                </View>
                            </TouchableWithoutFeedback>
                            <TouchableWithoutFeedback>
                                <View style={[styles.featuresCell]}>
                                    <Image style={styles.featuresImage} source={require('../../assets/image/icon28.png')}></Image>
                                    <Text style={styles.featuresTexy}>语音聊天</Text>
                                </View>
                            </TouchableWithoutFeedback>
                            <TouchableWithoutFeedback>
                                <View style={[styles.featuresCell]}>
                                    <Image style={styles.featuresImage} source={require('../../assets/image/icon25.png')}></Image>
                                    <Text style={styles.featuresTexy}>视频聊天</Text>
                                </View>
                            </TouchableWithoutFeedback>
                            <TouchableWithoutFeedback onPress={() => this.sendRedPacketInRefs.current.setOpen(true)}>
                                <View style={[styles.featuresCell]}>
                                    <Image style={styles.featuresImage} source={require('../../assets/image/icon23.png')}></Image>
                                    <Text style={styles.featuresTexy}>红包</Text>
                                </View>
                            </TouchableWithoutFeedback>
                            <TouchableWithoutFeedback onPress={() => showModal(<NavigateModalSelect operation={
                                [
                                    { text: '站内转帐', onPress: () => this.props.navigation.navigate('friendTransferInApp', this.props.route.params) },
                                    // { text: '区块链转帐', onPress: () => console.log('FriendTransferInApp') },
                                ]
                            } />)}>
                                <View style={[styles.featuresCell]}>
                                    <Image style={styles.featuresImage} source={require('../../assets/image/icon29.png')}></Image>
                                    <Text style={styles.featuresTexy}>转帐</Text>
                                </View>
                            </TouchableWithoutFeedback>
                            <TouchableWithoutFeedback onPress={() => this.sendFriendContactCard()}>
                                <View style={[styles.featuresCell]}>
                                    <Image style={styles.featuresImage} source={require('../../assets/image/icon24.png')}></Image>
                                    <Text style={styles.featuresTexy}>名片</Text>
                                </View>
                            </TouchableWithoutFeedback>
                        </View>
                        }
                        {this.state.openEmoji && <EmojiSelectorList state={(el) => this.setState({ text: this.state.text + el })} />}
                    </View>
                </View>
                <FriendRedPacketInApp {...this.props} ref={this.sendRedPacketInRefs} />
                <ImageView
                    images={this.state.images}
                    imageIndex={0}
                    visible={this.state.visible}
                    onRequestClose={() => this.setState({ visible: false })}
                />
            </View>
        )
    }
}

const mapStateToProps = (state) => state.app

const mapDispatchToProps = {
    SetCuurentPersonalFriendPageInfo,
    SetPersonalFriendPageMsgItem,
    SetFriendMsg,
    syncPageGetFriendMsg,
    syncPageGetFriendMsgSeq,
    asyncGetFriendList
}

export default connect(mapStateToProps, mapDispatchToProps)(FriendMsg)


const styles = StyleSheet.create({
    headerTitle: {
        maxWidth: pTx(250),
    },
    message: {
        fontSize: 30,
        flex: 1,
        margin: 10,
        backgroundColor: '#FFF',
    },
    mainContent: {
        flex: 1,
        backgroundColor: 'rgba(237, 237, 237, 1)',
    },
    footRender: {
        paddingVertical: pTx(9),

        backgroundColor: "rgba(247, 247, 247, 1)",
    },
    footRenderRow: {
        flexDirection: "row",
        alignItems: "flex-end",
    },
    renderComposer: {
        flex: 1,
        flexDirection: "row",
        alignItems: "center",
    },
    composer: {
        flex: 1,
        fontSize: pTx(16),
        borderRadius: pTx(4),
        minHeight: pTx(40),
        paddingVertical: pTx(2),
        paddingHorizontal: pTx(10),
        backgroundColor: "#ffffff",
    },
    renderUserItem: {
        paddingVertical: pTx(10),
        flexDirection: "row",
        alignItems: "flex-start"
    },
    renderUserItemRowReverse: {
        flexDirection: "row-reverse",
    },
    renderAvatar: {
        paddingHorizontal: pTx(15),
    },
    avatar: {
        height: pTx(40),
        width: pTx(40),
        borderRadius: pTx(8),
    },
    messageText: {
        paddingVertical: pTx(10),
        fontSize: pTx(15),
        color: "#333333",
        paddingHorizontal: pTx(10),
        backgroundColor: "#ffffff",
        borderRadius: pTx(8),
        maxWidth: pTx(260),
    },
    youNotFriendText: {
        paddingHorizontal: pTx(20),
        textAlign: "center",
        opacity: 0.6,
        fontSize: pTx(12),
    },


    sendBtn: {
        paddingHorizontal: pTx(12),
        marginBottom: pTx(5),
        height: pTx(30),
        fontSize: pTx(16),
        color: "#fff",
        backgroundColor: "rgba(6, 193, 97, 1)",
        borderRadius: pTx(4),
        textAlignVertical: "center"
    },
    containerStyle: {
        backgroundColor: "#EDEDED",
        paddingVertical: pTx(8),
    },
    textInputStyle: {
        fontSize: pTx(16),
        borderRadius: pTx(4),
        minHeight: 0,
        paddingVertical: pTx(5),
        paddingHorizontal: pTx(10),
        marginVertical: 0,
        backgroundColor: "#ffffff",
    },
    rightRenderSend: {
        marginHorizontal: pTx(10),
        flexDirection: "row",
        alignItems: "center"
    },
    footImage: {
        marginRight: pTx(8),
        marginBottom: pTx(4),
        width: pTx(30),
        height: pTx(30),
    },


    moreFeatures: {
        flexDirection: "row",
        flexWrap: "wrap",
        columnGap: pTx(32),
        paddingHorizontal: pTx(27),
        paddingTop: pTx(13),
    },
    featuresCell: {
        marginVertical: pTx(8),
        alignItems: "center",
    },
    featuresImage: {
        height: pTx(53),
        width: pTx(53),
    },
    featuresTexy: {
        marginTop: pTx(5),
        textAlign: "center",
        fontSize: pTx(12),
        color: "#727272"
    },

    imageEqually: {
        marginTop: pTx(5),
    },
    backgroundVideo: {
        width: pTx(150),
        height: pTx(100),
        backgroundColor: "#000"
    },
    RedPacketBox: {
        flex: 1,
        flexDirection: "row",
        justifyContent: "center"
    },
    RedPacket: {
        textAlign: "center",
        fontSize: pTx(12),
    }
});

